import chardet
import re


def Handle_single_comment(lines, i):
    index = lines[i].find("//")
    if index != -1:
        # lines[i] = lines[i][0:index]
        lines[i] = lines[i].replace(lines[i], '', 1)
        lines[i] += ''


def Handle_document_comment(lines, i):
    global flag
    while True:
        if not flag:
            index = lines[i].find("/*")
            if index != -1:
                flag = True
                index2 = lines[i].find("*/", index + 2)
                if index2 != -1:
                    lines[i] = lines[i].replace(lines[i], '', 1)
                    flag = False  # continue look for comment
                else:
                    lines[i] = lines[i].replace(lines[i], '', 1)  # only find "begin comment
                    lines[i] += ''
                    return -2
            else:
                return 0  # not find
        else:
            index2 = lines[i].find("*/")
            if index2 != -1:
                flag = False
                lines[i] = lines[i].replace(lines[i], '', 1)  # continue look for comment
            else:
                return -1  # should delete this


def RemoveComment(file):
    global flag
    f = open(file, "r")
    lines = f.readlines()
    f.close()
    length = len(lines)
    i = 0
    while i < length:
        ret = Handle_document_comment(lines, i)
        if ret == -1:
            if flag == False:
                print("There must be some wrong")
            del lines[i]
            i -= 1
            length -= 1
        elif ret == 0:
            Handle_single_comment(lines, i)
        else:
            pass
        i += 1


def writeResult(file, lines):
    f = open(file, "w")
    for line in lines:
        if line == '':  # 遇到空格忽略，跳出该次循环
            continue
        f.write(line)
    f.close()


def Output(lines):
    for line in lines:
        if line == '':
            continue
        print(line)


def sql_filter(raw_sql):
    """
    :param raw_sql: 需要处理的sql语句
    :return: 过滤以后的sql语句
    """
    # print(raw_sql)
    raw_sql = raw_sql.strip("\n")
    raw_sql = re.sub(r'//.*', "", raw_sql)
    raw_sql = re.sub(r'/.*', "", raw_sql)
    return raw_sql


def convert_to_uft8(input_file, output_file):
    """
    :param input_file:
    :param output_file:
    :return:
    """
    try:
        f = open(input_file, 'rb')
        for data in f.readline():
            result = chardet.detect(data)
            print(data)
            encoding = result['encoding']
            print("文件：{}，编码为：{}".format(input_file, encoding))

            # 过滤
            _data = data.decode(encoding)
            sql_filter(_data)

        f.close()

        # 重新写入文件
        dest_file = open(output_file, 'w', encoding='utf-8')
        dest_file.write(_data)

    except Exception as e:
        # logging.error(e)
        print(e)
        if data:
            f.close()
        return False


if __name__ == '__main__':
    in_file = 'input.txt'
    out_file = 'output.txt'
    if convert_to_uft8(in_file, out_file):
        print("转换成功")
